package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.R;
import com.example.hcd.adapt.FlowMyAdapt;
import com.example.hcd.datamanage.TaskTodoInfo;
import com.example.hcd.internet.InternetKeep;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.ImageBtnMove;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.OnDoubleClickListener;
import com.example.hcd.tool.ToastHelp;
import com.example.hcd.tool.XListView;
import com.example.hcd.tool.XListView.IXListViewListener;
import com.wheel.StrericWheelAdapter;
import com.wheel.WheelView;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FlowMyActivity extends BaseActivity implements OnClickListener,OnItemClickListener,OnDoubleClickListener,IXListViewListener{ 
	private FlowMyActivity context;
	private LayoutInflater inflater;
	private View main_view;
	// 列表类型
//	my_reimburse_list 我的报销列表
//	all_reimburse_list 所有人的报销列表
//	all_reimburse_todo 报销待办
//	my_payment_list 我的付款列表
//	all_payment_list 所有人的付款列表
//	all_payment_todo 付款待办
//	my_borrow_list 我的借款列表
//	all_borrow_list 所有人的借款列表
//	all_borrow_todo 借款待办
//	my_purchase_list 我的采购列表
//	all_purchase_list 所有人的采购列表
//	all_purchase_todo 采购待办
//	all_sealuse_list 所有人的用章列表
//	all_sealuse_todo 用章待办
//  all_task_todo 所有待办任务
	
	private String type;

	private TextView title_content;

	private XListView list;
	
	private int currentPage = 1;
	
	private FlowMyAdapt adapt;
	
	//滚动时间
	private WheelView yearWheel,monthWheel,dayWheel;
	public static String[] yearContent=null;
	public static String[] monthContent=null;
	public static String[] dayContent=null;
	
	
	private long startTime_l =0;
	private long endTime_l =0;
	
	private String id;
	
	private String people_name;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mPageName = "FlowMyActivity";
		// 初始化
		context = this;
		inflater = LayoutInflater.from(this);
		main_view = inflater.inflate(R.layout.my_task_list_view, null);
		setContentView(main_view);
		type = getIntent().getStringExtra("TASK_TYPE");
		title_content = (TextView) findViewById(R.id.title_content);
		list = (XListView) findViewById(R.id.lists);
		list.setPullLoadEnable(true);
		list.setXListViewListener(this);
		list.setOnItemClickListener(this);
		//
		// 返回键
		ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
		// 刷新
		ImageView refreshBtn = (ImageView) findViewById(R.id.title_bar_btn_right);
		backBtn.setOnClickListener(context);
		refreshBtn.setOnClickListener(context);
		
		initList();
		
		
		
	}

	public void initList() {
		if (type.equals("") || type == null) {
			//Toast.makeText(context, "未知的类型", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(context, "未知的类型");
			return;
		} else {
			LoadTaskInfoList list = new LoadTaskInfoList(context,1);
			list.execute();
		}
		
		
		RelativeLayout scroll = (RelativeLayout)main_view.findViewById(R.id.scorllView);
		ImageBtnMove btn = new ImageBtnMove(this);
		btn.setActivity(this);
		btn.setListen(this);
		btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.search));
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(100, 100);
        layoutParams.topMargin=200;
        layoutParams.leftMargin=8;
        layoutParams.rightMargin=8;
        layoutParams.bottomMargin=8;
		scroll.addView(btn,layoutParams);
		
		initContent();
	}
	
	public void initContent()
	{
		yearContent = new String[10];
		for(int i=0;i<10;i++)
			yearContent[i] = String.valueOf(i+2013);
		
		monthContent = new String[12];
		for(int i=0;i<12;i++)
		{
			monthContent[i]= String.valueOf(i+1);
			if(monthContent[i].length()<2)
	        {
				monthContent[i] = "0"+monthContent[i];
	        }
		}
			
		dayContent = new String[31];
		for(int i=0;i<31;i++)
		{
			dayContent[i]=String.valueOf(i+1);
			if(dayContent[i].length()<2)
	        {
				dayContent[i] = "0"+dayContent[i];
	        }
		}	
		
	}

	
	//初始化任务办理相关
	public void refreshTasktodoList()
	{
		ArrayList<TaskTodoInfo> data = InternetKeep.getInstence().getTaskTodoInfoListCatch();
		
		adapt.addList(data);
		
	}
	public void initTaskTodoItem()
	{
		if (type.equals("my_flow_todo")) 
		{
			title_content.setText("经办流程");
		}
		
		
		adapt = new FlowMyAdapt(context);
		ArrayList<TaskTodoInfo> data = InternetKeep.getInstence().getTaskTodoInfoListCatch();
		
		adapt.setList(data);
		list.setAdapter(adapt);
		
		if(data.size()==0)
		{
			list.removeFooterViews();
		}
	}
	
	

	private class LoadTaskInfoList extends AsyncTask<String, Integer, String> {

		private Context context;
		private int index;
		private MyLoadingDialog dialog;
		public LoadTaskInfoList(Context context, int index) {
			this.context = context;
			this.index = index;
		}

		@Override
		protected void onPreExecute() {
			dialog = new MyLoadingDialog(context, null, "加载中...", false);
			dialog.setPullToRefreshListView(list);
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try {
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				//vs.add(new BasicNameValuePair("taskId", taskId));
				vs.add(new BasicNameValuePair("currentPage", ""+currentPage));
		
				String uri = URLS.getFlowhandel();
				if(startTime_l >0)
				{
					vs.add(new BasicNameValuePair("beginTime",""+startTime_l));
					uri = URLS.getSearchFlowhandel();
				}
				
				if(endTime_l >0)
				{
					vs.add(new BasicNameValuePair("endTime", ""+endTime_l));
					uri = URLS.getSearchFlowhandel();
				}
				
				if(id !=null)
				{
					vs.add(new BasicNameValuePair("searchId", id));
					uri = URLS.getSearchFlowhandel();
				}
				
				if(people_name !=null)
				{
					vs.add(new BasicNameValuePair("name", people_name));
					uri = URLS.getSearchFlowhandel();
				}

				response = LinkHelp.post(uri, vs, false);
				if (response != null) {
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						result = sb.toString();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
						
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dimiss();
			if(dialog.mCancel)
			{
				return;
			}
			
			if (!TextUtils.isEmpty(result)) {

				if (result.contains("error")) 
				{
					onLoad();
					
					try {
						JSONObject obj = new JSONObject(result);
						String msg = obj.getString("msg");
						ToastHelp.doToast(FlowMyActivity.this, msg);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {

					if(index >1)
					{
						
							InternetKeep.getInstence().ParseMyProcess(result);
							refreshTasktodoList();
						
							onLoad();
					}else
					{
						InternetKeep.getInstence().clearCacheData();

							InternetKeep.getInstence().clearCacheData();
							InternetKeep.getInstence().ParseMyProcess(result);
							initTaskTodoItem();
						
							onLoad();
					}
	
					if(InternetKeep.getInstence().isHaveNextPage)
					{
						list.removeFooterViews();
					}
				}

			}else
			{
					ToastHelp.doToast(FlowMyActivity.this, "网络异常！");
			}
		}

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		int id = arg0.getId();
		switch (id) {
		case R.id.title_bar_btn_left:
			finish();
			break;
			
		case R.id.title_bar_btn_right:
			new LoadTaskInfoList(context, currentPage=1).execute();
			break;

		default:
			break;
		}
		
		
		
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view,int position, long id) {
		// TODO Auto-generated method stub
//
//		adapter.get
		TaskTodoInfo data = adapt.getItem(position-1);
		Intent intent = new Intent(context, TaskInfo.class);
		intent.putExtra("taskId", data.getId_());
		intent.putExtra("processId", data.getProc_INST_ID_());
		intent.putExtra("TASK_TYPE", data.getKey());
		if(data.getKey().equals("sealApp"))
		{
			intent.putExtra("task_DEF_KEY_", data.getTask_DEF_KEY_());
		}
		intent.putExtra("IS_TASK_TODO", false);
		startActivity(intent);
	}

	@Override
	public void onRefresh() {
		list.addFooterViews();
		new LoadTaskInfoList(context, currentPage=1).execute();
				
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		if(!InternetKeep.getInstence().isHaveNextPage)
		{
			currentPage++;
			new LoadTaskInfoList(context, currentPage).execute();
		}else
		{
			Toast.makeText(context, "已经到最后", Toast.LENGTH_SHORT).show();
			onLoad();
		}
	}
	
	private void onLoad() {
		SimpleDateFormat format = new SimpleDateFormat(
				"yyyy年MM月dd日  HH:mm");
		String date = format.format(new Date());
		list.stopRefresh();
		list.stopLoadMore();
		list.setRefreshTime(date);
	}

	@Override
	public void OnSingleClick(View v) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void OnDoubleClick(View v) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
				final AlertDialog userDia = new AlertDialog.Builder(FlowMyActivity.this).create();
				userDia.show();
				//下面两行代码加入后即可弹出输入法 
				userDia.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); 
				userDia.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
				View alertView = inflater.inflate(R.layout.task_search_view, null);
				userDia.getWindow().setContentView(alertView);
				
				
				alertView.findViewById(R.id.search_by_id).setVisibility(View.VISIBLE);
				
				alertView.findViewById(R.id.search_by_people).setVisibility(View.VISIBLE);
				
				final EditText idEdit = (EditText)alertView.findViewById(R.id.edittext1);
				final EditText nameEdit = (EditText)alertView.findViewById(R.id.edittext2);
				//idEdit.setFocusable(true);
				final TextView startTime = (TextView)alertView.findViewById(R.id.textView3);
				startTime.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						View view = ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.date_choose_view, null); 
						
			    		Calendar calendar = Calendar.getInstance();
			    	    int curYear = calendar.get(Calendar.YEAR);
			            int curMonth= calendar.get(Calendar.MONTH)+1;
			            int curDay = calendar.get(Calendar.DAY_OF_MONTH);

			     	    
			    	    yearWheel = (WheelView)view.findViewById(R.id.yearwheel);
			    	    monthWheel = (WheelView)view.findViewById(R.id.monthwheel);
			    	    dayWheel = (WheelView)view.findViewById(R.id.daywheel);

			            AlertDialog.Builder builder = new AlertDialog.Builder(FlowMyActivity.this);  
			            builder.setView(view); 
			            
			            yearWheel.setAdapter(new StrericWheelAdapter(yearContent));
					 	yearWheel.setCurrentItem(curYear-2013);
					    yearWheel.setCyclic(true);
					    yearWheel.setInterpolator(new AnticipateOvershootInterpolator());
				        
				 
				        monthWheel.setAdapter(new StrericWheelAdapter(monthContent));
				       
				        monthWheel.setCurrentItem(curMonth-1);
				     
				        monthWheel.setCyclic(true);
				        monthWheel.setInterpolator(new AnticipateOvershootInterpolator());
				        
				        dayWheel.setAdapter(new StrericWheelAdapter(dayContent));
				        dayWheel.setCurrentItem(curDay-1);
				        dayWheel.setCyclic(true);
				        dayWheel.setInterpolator(new AnticipateOvershootInterpolator());

				        builder.setTitle("选取时间");  
				        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {  

				        	@Override  
			            	public void onClick(DialogInterface dialog, int which) {  
			            	
				        		StringBuffer sb = new StringBuffer();  
				        		sb.append(yearWheel.getCurrentItemValue()).append("-")
				        		.append(monthWheel.getCurrentItemValue()).append("-")
				        		.append(dayWheel.getCurrentItemValue());
			     
				        		startTime.setText(sb);
				        		dialog.cancel();  
			            	}  
				        });  
			       
				        builder.show();
					}
				});
				
				
				
				final TextView endTime = (TextView)alertView.findViewById(R.id.textView4);
				
				endTime.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						View view = ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.date_choose_view, null); 
						
			    		Calendar calendar = Calendar.getInstance();
			    	    int curYear = calendar.get(Calendar.YEAR);
			            int curMonth= calendar.get(Calendar.MONTH)+1;
			            int curDay = calendar.get(Calendar.DAY_OF_MONTH);

			     	    
			    	    yearWheel = (WheelView)view.findViewById(R.id.yearwheel);
			    	    monthWheel = (WheelView)view.findViewById(R.id.monthwheel);
			    	    dayWheel = (WheelView)view.findViewById(R.id.daywheel);

			            AlertDialog.Builder builder = new AlertDialog.Builder(FlowMyActivity.this);  
			            builder.setView(view); 
			            
			            yearWheel.setAdapter(new StrericWheelAdapter(yearContent));
					 	yearWheel.setCurrentItem(curYear-2013);
					    yearWheel.setCyclic(true);
					    yearWheel.setInterpolator(new AnticipateOvershootInterpolator());
				        
				 
				        monthWheel.setAdapter(new StrericWheelAdapter(monthContent));
				       
				        monthWheel.setCurrentItem(curMonth-1);
				     
				        monthWheel.setCyclic(true);
				        monthWheel.setInterpolator(new AnticipateOvershootInterpolator());
				        
				        dayWheel.setAdapter(new StrericWheelAdapter(dayContent));
				        dayWheel.setCurrentItem(curDay-1);
				        dayWheel.setCyclic(true);
				        dayWheel.setInterpolator(new AnticipateOvershootInterpolator());

				        builder.setTitle("选取时间");  
				        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {  

				        	@Override  
			            	public void onClick(DialogInterface dialog, int which) {  
			            	
				        		StringBuffer sb = new StringBuffer();  
				        		sb.append(yearWheel.getCurrentItemValue()).append("-")
				        		.append(monthWheel.getCurrentItemValue()).append("-")
				        		.append(dayWheel.getCurrentItemValue());
			     
				        		endTime.setText(sb);
				        		dialog.cancel();  
			            	}  
				        });  
			       
				        builder.show();
					}
				});
				
				TextView sureBtn = (TextView)alertView.findViewById(R.id.textView6);
				sureBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						if((startTime.getText().toString().equals("")||startTime.getText().toString()==null)&&
								(endTime.getText().toString().equals("")||endTime.getText().toString()==null)	)
						{
							userDia.dismiss();
						}else
						{
							if(startTime.getText().toString().equals("起始时间"))
							{
								try {
									SimpleDateFormat mFormat= new SimpleDateFormat("yyyy-MM-dd");
									//继续转换得到秒数的long型  
									Date time = mFormat.parse("2000-01-01");
									
									startTime_l = time.getTime();
									
								} catch (Exception e) {
									// TODO: handle exception
								} 
							}else
							{
								try {
									SimpleDateFormat mFormat= new SimpleDateFormat("yyyy-MM-dd");
									//继续转换得到秒数的long型  
									Date time = mFormat.parse(startTime.getText().toString());
									
									startTime_l = time.getTime();
									
								} catch (Exception e) {
									// TODO: handle exception
								} 
							}
							
							if(endTime.getText().toString().equals("结束时间"))
							{
								try {
									SimpleDateFormat mFormat= new SimpleDateFormat("yyyy-MM-dd");
									//继续转换得到秒数的long型  
									String times = mFormat.format(new Date());
									Date time = mFormat.parse(times);
									
									endTime_l = time.getTime();
									
								} catch (Exception e) {
									// TODO: handle exception
								} 
							}else
							{
								try {
									SimpleDateFormat mFormat= new SimpleDateFormat("yyyy-MM-dd");
									//继续转换得到秒数的long型  
									Date time = mFormat.parse(endTime.getText().toString());
									
									endTime_l = time.getTime();
									
								} catch (Exception e) {
									// TODO: handle exception
								}
							}
							
							
							if(idEdit.getText().toString()!=null&&!idEdit.getText().toString().equals(""))
							{
								id = idEdit.getText().toString();
							}else
							{
								id = null;
							}
							
							if(nameEdit.getText().toString()!=null&&!nameEdit.getText().toString().equals(""))
							{
								people_name = nameEdit.getText().toString();
							}else
							{
								people_name = null;
							}
							
							
							//System.out.println(startTime_l+"========"+endTime_l);
							onRefresh();
							userDia.dismiss();
							
						}
					}
				});
				
				TextView cancelBtn = (TextView)alertView.findViewById(R.id.textView7);
				cancelBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						userDia.dismiss();
					}
				});
	}

}
